package orm

import (
	"fmt"
	"reflect"
	"strings"
)

type Where interface {
	GetWhereSqlAndValue() (string,[]interface{})
}
func  CreateOp(op string,val interface{}) []interface{}{
	return []interface{}{op,val}
}

type XORMTransfer struct {
	structOjb interface{}
	where []string
	values []interface{}
	ops []interface{}
}
func NewXORMTransfer(obj interface{}) XORMTransfer {
	return XORMTransfer{structOjb: obj}
}
func (xorm XORMTransfer) GetWhereSqlAndValue() (string,[]interface{}){
	value := reflect.ValueOf(xorm.structOjb)
	for i := 0; i < value.NumField(); i++ {
		tmp := value.Type().Field(i)
		field := tmp.Tag.Get("column")
		if field == "" {
			field = strings.ToLower(tmp.Name)
		}
		params := value.Field(i)
		if params.IsNil() {
			continue
		}
		data := params.Interface()
		sql,vals := xorm.opTransfer(field,data.([]interface{}))
		xorm.where  = append(xorm.where,sql)
		xorm.values  = append(xorm.values,vals...)
	}
	finalSql := strings.Join(xorm.where," AND ")
	return finalSql,xorm.values
}
func (xorm XORMTransfer) opTransfer (key string,params []interface{}) (string,[]interface{}) {
	t1,err := params[0].(string)
	if err == true {
		if t1 == "IN" || t1 == "in" || t1 == "NOT IN" || t1 == "not int" {
			var plen int
			var eles []interface{}
			switch pdata := params[1].(type) {
			case []int:
				plen = len(pdata) -1
				for _,v := range pdata{
					eles = append(eles,v)
				}
			case []int32:
				plen = len(pdata) -1
				for _,v := range pdata{
					eles = append(eles,v)
				}
			case []int64:
				plen = len(pdata) -1
				for _,v := range pdata{
					eles = append(eles,v)
				}
			case []string:
				plen = len(pdata) -1
				for _,v := range pdata{
					eles = append(eles,v)
				}
			}
			tmpStr := ""
			for i:=0;i<=plen;i++ {
				if i == plen {
					tmpStr = tmpStr+"?"
				} else {
					tmpStr = tmpStr+"?,"
				}
			}
			tmpStr = key+" "+t1+"("+tmpStr+")"
			return tmpStr, eles
		} else {
			tmpStr := key+" "+t1+" ?"
			return tmpStr,params[1:]
		}
	}
	_,err = params[0].([]interface{})
	wheres := make([]string,0);
	values := make([]interface{},0)
	for _,ops := range params {
		fmt.Println(ops)
		switch v := ops.(type) {
		case []interface{}:

			sql,vals := xorm.opTransfer(key,v)
			wheres = append(wheres,sql)
			values = append(values,vals...)
		}
	}
	whereStr := strings.Join(wheres," AND ")
	return whereStr,values
}



